<template>
	<div class="fillcontain">
		<el-row style="height: calc(100% - 70px)" :gutter="16">
			<el-col :span="4" style="height: calc(100% - 70px)">
				<div class="grid-content">
					<el-input
						v-model="searchKey"
						placeholder="输入数据集名称"
						@blur="getDataSet"
						style="margin-left: 10px; margin-bottom: 10px; width: 100%"
					></el-input>
					<ul>
						<li
							v-for="(data, index) in datasetListData"
							:key="index"
							:class="index ? 'dataset-item' : 'dataset-item dataset-action'"
							@click="datasetChange(data, index)"
						>
							<span>{{ data.label }}</span>
							<i class="el-icon-arrow-right"></i>
						</li>
					</ul>
				</div>
			</el-col>
			<el-col :span="20">
				<div class="search_select">
					<div class="search_input">
						<span class="span-label">表名称:</span>
						<el-input v-model="form.input" placeholder="输入表名称"> </el-input>
					</div>
					<div class="search_input">
						<span class="span-label">核验状态:</span>
						<el-select v-model="form.checkStatus" placeholder="请选择">
							<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
						</el-select>
					</div>
					<div class="search_input">
						<span class="span-label">版本时间:</span>
						<el-select v-model="form.versionTime" placeholder="请选择">
							<el-option v-for="item in vTimeListData" :key="item.value" :label="item.label" :value="item.value"> </el-option>
						</el-select>
					</div>
					<div class="search_input">
						<el-button type="primary" @click="search">查询</el-button>
						<el-button @click="resets">重置</el-button>
					</div>
				</div>
				<div class="table_container">
					<div style="line-height: 40px; font-size: 14px">
						<span>当前所属数据集：{{ datasetName.datasetCode }}</span>
						<div style="float: right">
							<el-button v-auth="'data-qa-fe:fieldCrossTavleManage:check'" type="primary" @click="crossShow = true">跨表核验</el-button>
							<el-button v-auth="'data-qa-fe:fieldCrossTavleManage:add'" type="primary" @click="add">新增数据表</el-button>
						</div>
					</div>
					<el-table v-loading="loading" :data="tableData" border :row-key="row => row.index" style="width: 100%; margin-top: 8px">
						<el-table-column label="表名称" prop="datasetTableName">
							<!-- <template #default="scope">
								<span style="color: rgba(15, 64, 245, 1); cursor: pointer">{{ scope.row.datasetTableName }}</span>
							</template> -->
						</el-table-column>
						<el-table-column label="表名" prop="datasetTableCode"> </el-table-column>
						<el-table-column label="字段数量" prop="fieldCnt" width="100"> </el-table-column>
						<el-table-column label="备注" prop="datasetTableDescription"> </el-table-column>
						<el-table-column label="版本时间" prop="versionId" width="110"> </el-table-column>
						<el-table-column label="核验状态" prop="invalidFlag" width="120">
							<template #default="scope">
								<el-switch v-model="scope.row.invalidFlag" active-value="0" inactive-value="1" @change="statusChange($event, scope.row)"></el-switch>
								<span style="margin-left: 10px">
									{{ scope.row.invalidFlag === '0' ? '开' : '关' }}
								</span>
							</template>
						</el-table-column>
						<el-table-column label="更新时间" prop="updateTime"> </el-table-column>
						<el-table-column label="操作" width="160">
							<template #default="scope">
								<el-button v-auth="'data-qa-fe:fieldCrossTavleManage:edit'" link size="small" type="primary" @click="handleEdit(scope.row)"
									>编辑</el-button
								>
								<el-button v-auth="'data-qa-fe:fieldCrossTavleManage:delete'" link size="small" type="primary" @click="handleDelete(scope.row)"
									>删除</el-button
								>
							</template>
						</el-table-column>
					</el-table>
					<el-pagination
						:current-page="currentPage"
						:page-sizes="[10, 20, 50, 100, 200]"
						:page-size="limit"
						:total="count"
						layout="total, sizes, prev, pager, next, jumper"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
					>
					</el-pagination>
				</div>
			</el-col>
		</el-row>
		<el-dialog v-model="dialog.visible" :title="dialog.title" width="30%" :before-close="dialogClose">
			<Form ref="modalFormRef" :form-state="formState" :form-data="formData"></Form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialog.visible = false">取 消</el-button>
					<el-button type="primary" :loading="dialog.loading" @click="dialogSave">保 存</el-button>
				</span>
			</template>
		</el-dialog>
		<CrossCheck
			:diag-show="crossShow"
			:version-id="datasetName.versionId"
			:check-status="datasetName.invalidFlag"
			:set-id="datasetName.value"
			@close="close"
		></CrossCheck>
	</div>
</template>

<script lang="ts" setup>
import {
	getDataSheet,
	getDataSetList,
	save_rule_dataset_table,
	update_rule_dataset_table,
	delete_rule_dataset_table,
	get_table_times
} from '@/api/data-qa-fe/index'
import CrossCheck from './crossCheck.vue'
import Form from '@/components/Form/index.vue'
import { parseTime } from '@/utils/tool'
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus/es'

const modalFormRef: any = ref(null)
const dialog = ref({
	title: '创建表',
	visible: false,
	loading: false
})
const formState = ref({
	id: '',
	datasetId: '',
	datasetTableName: '',
	datasetTableCode: '',
	versionId: parseTime(new Date(), '{y}{m}{d}'),
	invalidFlag: '0',
	datasetTableDescription: ''
})
const formData = ref([
	{
		title: '数据集',
		dataIndex: 'datasetId',
		type: 'select',
		data: [],
		disabled: true,
		rules: [{ required: true, message: '请选择数据集', trigger: 'change' }]
	},
	{
		title: '表名称',
		dataIndex: 'datasetTableName',
		type: 'input',
		rules: [{ required: true, message: '请输入表名称', trigger: 'blur' }]
	},
	{
		title: '表名',
		dataIndex: 'datasetTableCode',
		type: 'input',
		rules: [{ required: true, message: '请输入表名', trigger: 'blur' }]
	},
	{
		title: '版本时间',
		dataIndex: 'versionId',
		type: 'day',
		disabled: true,
		format: 'YYYYMMDD'
	},
	{
		title: '核验状态',
		dataIndex: 'invalidFlag',
		type: 'switch',
		active: '0',
		inactive: '1'
	},
	{
		title: '备注',
		dataIndex: 'datasetTableDescription',
		type: 'textarea'
	}
])
const options = ref([
	{
		value: '',
		label: '全部'
	},
	{
		value: '0',
		label: '开启'
	},
	{
		value: '1',
		label: '关闭'
	}
])
const vTimeListData = ref([
	{
		value: '',
		label: '全部'
	}
])
const form = ref({
	input: '',
	checkStatus: '',
	versionTime: ''
})
const searchKey = ref('')
const loading = ref(true)
const value = ref('')
const count = ref(0)
const tableData = ref([])
const currentPage = ref(1)
const limit = ref(10)
const datasetListData = ref([])
const datasetName = ref({})
const crossShow = ref(false)
const oldState = ref('')

onMounted(() => {
	loading.value = false
	getDataSet()
})

const dialogClose = (done: Function) => {
	done()
}
const dialogReset = (item: any) => {
	const obj = {
		id: '',
		datasetId: '',
		datasetTableName: '',
		datasetTableCode: '',
		versionId: parseTime(new Date(), '{y}{m}{d}'),
		invalidFlag: '0',
		datasetTableDescription: ''
	}
	if (item) {
		oldState.value = item.invalidFlag
		formState.value = { ...obj, ...item }
	} else {
		oldState.value = ''
		formState.value = { ...obj, datasetId: datasetName.value.id }
		console.log('新增什么', formState.value)
	}
}
const dialogSaveBefore = async (name: any) => {
	if (formState.value.invalidFlag === '1' && oldState.value === '0') {
		return new Promise((resolve, reject) => {
			ElMessageBox.confirm(
				'关闭核验，则该数据集停止核验。此会影响所有与本数据集有关的字段核验，单表核验及跨表核验',
				`确认关闭[${name}]数据表核验吗？`,
				{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}
			)
				.then(() => {
					return resolve()
				})
				.catch(() => {
					console.log('取消')
					return reject()
				})
		})
	}
}
const dialogSave = async () => {
	try {
		dialog.value.loading = true
		await modalFormRef.value.submit()
		if (dialog.value.title === '编辑表') {
			await dialogSaveBefore(formState.value.datasetTableName)
		}
		let params = {
			...formState.value
		}
		let res
		if (dialog.value.title === '创建表') {
			res = await save_rule_dataset_table(params)
		} else {
			res = await update_rule_dataset_table(params)
		}
		if (res.code == 0) {
			ElMessage({
				message: res.msg,
				type: 'success'
			})
			dialog.value.loading = false
			dialog.value.visible = false
			init()
		} else {
			dialog.value.loading = false
			ElMessage({
				message: res.msg,
				type: 'error'
			})
		}
	} catch (e) {
		dialog.value.loading = false
		console.log(e)
	}
}
const add = () => {
	dialog.value.title = '创建表'
	dialogReset()
	dialog.value.visible = true
}
const handleEdit = (item: any) => {
	dialog.value.title = '编辑表'
	let obj: any = {}
	for (let key in formState.value) {
		obj[key] = item[key]
	}
	dialogReset(obj)
	dialog.value.visible = true
}
const handleDelete = (item: any) => {
	ElMessageBox.confirm('此操作确认删除后不可恢复，请谨慎操作！', `确认删除[${item.datasetTableName}]数据表吗？`, {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			const params = {
				id: item.id
			}
			delete_rule_dataset_table(params).then((res: any) => {
				if (res.code == 0) {
					init()
					ElMessage({
						type: 'success',
						message: '删除成功'
					})
				} else {
					ElMessage({
						type: 'error',
						message: res.msg
					})
				}
			})
		})
		.catch(() => {
			console.log('取消')
		})
}
const init = () => {
	let param = {
		limit: limit.value,
		page: currentPage.value,
		datasetId: datasetName.value.id,
		datasetTableName: form.value.input,
		invalidFlag: form.value.checkStatus,
		versionId: form.value.versionTime
	}
	getDataSheet(param).then((res: any) => {
		if (res.code == 0) {
			tableData.value = res.data.list
			count.value = res.data.total
		}

		getVTimes()
	})
}
const getVTimes = () => {
	let param = {
		tableName: 'data_qa_rule_dataset_table',
		dataSetId: datasetName.value.id
	}

	vTimeListData.value = [
		{
			value: '',
			label: '全部'
		}
	]

	get_table_times(param).then((res: any) => {
		console.log(res.data)
		if (res.code == 0) {
			vTimeListData.value = vTimeListData.value.concat(res.data)
		} else {
			vTimeListData.value = []
		}
	})
}
const getDataSet = () => {
	let param = {
		searchKey: searchKey.value
	}
	getDataSetList(param).then((res: any) => {
		if (res.code == 0) {
			res.data.forEach(item => {
				item.value = item.id
				item.label = item.datasetName
			})
			datasetListData.value = res.data
			datasetName.value = datasetListData.value[0]
			const item = formData.value.find(v => {
				return v.dataIndex === 'datasetId'
			})
			item.data = res.data
			init()
		} else {
			datasetListData.value = []
		}
	})
}
const handleSizeChange = (val: any) => {
	limit.value = val
	init()
}
const handleCurrentChange = (val: any) => {
	console.log(`当前页: ${val}`)
	currentPage.value = val
	init()
}
const search = () => {
	currentPage.value = 1
	init()
}
const resets = () => {
	form.value.input = ''
	form.value.checkStatus = ''
	form.value.versionTime = ''
	currentPage.value = 1
	limit.value = 10
	init()
}
const datasetChange = (data: any, index: number) => {
	datasetName.value = data
	const doms = document.getElementsByClassName('dataset-item')
	const attr_doms = Array.from(doms)
	if (attr_doms[index].className === 'dataset-item dataset-action') {
	} else {
		attr_doms.forEach(item => {
			item.className = 'dataset-item'
		})
		attr_doms[index].className = 'dataset-item dataset-action'
	}
	resets()
}
const statusChange = (value: any, data: any) => {
	console.log('啥呀', value, data)
	let param = {
		...data,
		invalidFlag: value
	}
	if (value === '1') {
		ElMessageBox.confirm(
			'关闭核验，则该数据表停止核验。此会影响所有与本数据表有关的字段核验，单表核验',
			`确认关闭【${data.datasetTableName}】核验吗？`,
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}
		)
			.then(() => {
				update_rule_dataset_table(param).then((res: any) => {
					if (res.code == 0) {
						data.invalidFlag = value
						ElMessage({
							type: 'success',
							message: '操作成功!'
						})
					}
				})
			})
			.catch(() => {
				data.invalidFlag = value == '1' ? '0' : '1'
				// this.$message({
				//   type: "error",
				//   message: "操作失败，请重试",
				// });
			})
	} else {
		update_rule_dataset_table(param).then((res: any) => {
			if (res.code == 0) {
				data.invalidFlag = value
			}
		})
	}
}
const close = () => {
	crossShow.value = false
}
</script>

<style lang="scss" scoped>
.fillcontain {
	background: #fff;
}
.grid-content {
	height: 100%;
	padding: 20px 10px 0 0;
	ul {
		height: 600px;
		overflow: auto;
		.dataset-item {
			line-height: 40px;
			padding-left: 10px;
			font-size: 14px;
			cursor: pointer;
			display: flex;
			justify-content: space-between;
			align-items: center;
			span {
				display: inline-block;
				width: 80%;
			}
		}

		.dataset-action {
			color: #fff;
			background: #667afa;
		}
	}
}
.search_select {
	padding: 20px 20px 20px 0;
	display: flex;
	flex-wrap: wrap;
	.search_input {
		margin-bottom: 15px;
		margin-right: 15px;
	}
	.span-label {
		margin: 0 10px 0 20px;
	}
}
.el-input,
.el-input__inner {
	width: auto;
}
.demo-table-expand {
	font-size: 0;
}
.demo-table-expand label {
	width: 90px;
	color: #99a9bf;
}
.demo-table-expand .el-form-item {
	margin-right: 0;
	margin-bottom: 0;
	width: 50%;
}
.table_container {
	padding: 10px 20px 20px;
}
</style>
